package dao

import (
	"blog/models"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

type Manager interface {
	AddUser(user *models.User)
	Login(username string) models.User
}

type manager struct {
	db *gorm.DB
}
var Mgr Manager // 接口类型
func init() {
	//  mysql连接语句
	dsn := "root:root@tcp(192.168.0.7:3309)/golang_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("无法初始化数据库连接: ", err)
	}
	// 此结构体类型实现了此接口
	Mgr = &manager{db: db}
	db.AutoMigrate(&models.User{})
}

func (mgr *manager) AddUser(user *models.User) {
	mgr.db.Create(user)
}

func (mgr *manager) Login(username string) models.User {
	var user models.User
	mgr.db.Where("username=?", username).First(&user)
	return user

}
